<?php

namespace App\Http\Controllers\OpenShop\Notify;

use App\Http\Controllers\BaseController;
use App\Http\Validate\SystemNotify\SystemNotifyValidate;
use App\Models\Article\ArticleModel;
use App\Models\System\SystemNoticesModel;
use App\Models\System\SystemNotifyCenterLogsModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Service\System\SystemNoticeService;
use App\Service\System\SystemNotifyService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class SystemNotifyController extends BaseController
{
    /**
     * 参数配置
     *
     * @return JsonResponse
     */
    public function configTemp()
    {
        return $this->success(SystemNotifyService::configTemp());
    }

    /**
     * 列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {
        $pageNum     = (int)$request->get('pageNum', 1);
        $pageSize    = (int)$request->get('pageSize', 10);
        $type        = $request->get('type', 0);
        $status      = $request->get('status', 0);
        $title       = $request->get('title', '');
        $sendAtStart = $request->get('sendAtStart', 0);
        $sendAtEnd   = $request->get('sendAtEnd', 0);
        $method      = $request->get('method', 0);
        $id          = (int)$request->get('id', 0);

        return $this->success(SystemNotifyService::list($pageNum, $pageSize,
            [
                'title'       => $title,
                'type'        => $type,
                'status'      => $status,
                'sendAtStart' => $sendAtStart,
                'sendAtEnd'   => $sendAtEnd,
                'method'      => $method,
                'id'          => $id
            ]));
    }

    /**
     * 新增
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function save(Request $request)
    {
        $this->validate($request, [
            'title'        => 'required|string|max:50',
            'type'         => 'required|numeric',
            'target'       => 'required|numeric',
            'pushType'     => "required|int|in:0,1,2,3",
            'presenceArea' => "string|max:20",
//            'url'          => 'exclude_unless:pushType,' . SystemNotifyCenterModel::PUSH_TYPE_2 . "|required|string|url",
            'content'      => 'exclude_unless:pushType,' . SystemNotifyCenterModel::PUSH_TYPE_3 . "|required|string|min:0",
            'pushTargetId' => [
                'exclude_unless:pushType,' . SystemNotifyCenterModel::PUSH_TYPE_1,
                "required",
                Rule::exists((new ArticleModel())->getTable(), "id")
            ],
            'summary'      => "sometimes|string|max:128",
            'pushTitle'    => 'sometimes|string|max:50',
        ]);

        $title       = $request->get('title');
        $id          = $request->get('id', 0);
        $target      = $request->get('target');
        $smsTemplate = $request->get('smsTemplate', '');
        $type        = $request->get('type');
        $pushTitle   = $request->get('pushTitle', '');
        $url         = $request->get('url', '');
        //消息添加默认为手动
        $method          = $request->get('method', SystemNotifyCenterModel::METHOD_TYPE_MANUAL);
        $summary         = $request->get('summary', '');
        $content         = $request->get('content', '');
        $isPopup         = $request->get('isPopup', '');
        $presenceArea    = $request->get('presenceArea', '');
        $isOffPop        = (int)$request->get('isOffPop', false);                  //是否关闭弹窗
        $popEffectiveDay = (int)$request->get('popEffectiveDay', 7);               //弹窗有效期天数-默认7天
        $region          = $request->get('region');                                //分公司-省市
        $pushTargetId    = (int)$request->post("pushTargetId", 0);
        $pushType        = (int)$request->post("pushType", 0);


        $notify = SystemNotifyService::save(
            $id, $title, $type, $target, $smsTemplate, $pushTitle, $url, $method, $summary,
            $content, $isPopup, $presenceArea, 0, [], $isOffPop, $popEffectiveDay, $region,
            $pushType, $pushTargetId
        );

        SystemNotifyService::recordLog($notify, '创建消息');

        return $this->success(["id" => $notify->id]);
    }

    /**
     * 正式推送
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function push(Request $request)
    {
        $id = $request->get('id', 0);

        SystemNotifyService::send($id);

        return $this->success();
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function delayPush(Request $request): JsonResponse
    {
        SystemNotifyService::delayPush(SystemNotifyValidate::delayPushValidate($request->all()));
        return $this->success();
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function cancelDelayPush(Request $request): JsonResponse
    {
        SystemNotifyService::cancelDelayPush(SystemNotifyValidate::cancelDelayPushValidate($request->all()));
        return $this->success();
    }

    /**
     * 关闭
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function close(Request $request)
    {
        $id = $request->get('id', 0);

        SystemNotifyService::close($id);
        return $this->success();
    }

    /**
     * 预推送
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function prePush(Request $request)
    {
        $id = $request->get('id', 0);

        $targetList = $request->get('userIds', 0);
        $targetList = explode(',', $targetList);

        SystemNotifyService::preSend($id, $targetList);

        return $this->success();
    }

    /**
     * 获取日志
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getLog(Request $request)
    {
        $id = $request->get('id', 0);

        $list = SystemNotifyCenterLogsModel::query()
                                           ->where('notifyCenterId', $id)
                                           ->orderBy('id', 'desc')
                                           ->select([
                                               'title',
                                               'createdAt',
                                               'createdBy'
                                           ])->get();

        return $this->success(['list' => $list]);
    }

    public function statistical(Request $request)
    {
        $id       = (int)$request->get('id', 0);
        $type     = (int)$request->get('type', 1); // 1:所有数据 2:已读 3:未读
        $pageNum  = (int)$request->get('pageNum', 1);
        $pageSize = (int)$request->get('pageSize', 10);

        $list = SystemNotifyService::statistical($pageNum, $pageSize, $id, $type);

        return $this->success($list);
    }
}

